<template>
	<view class="userInfoEdit">
		<view class="userInfoEdit_haber" :style="{ paddingTop: (top+30) + 'px' }">
			<tui-navigation-bar maxOpacity="0" :titleSize="18" :titleLineHeight="18" :titlefontWeight="800"
				@init="initNavigation" title="编辑" backgroundColor="#fff" color="#000">
				<view class="tui-header-icon" :style="{ marginTop: top + 'px' }">
					<tui-icon name="arrowleft" color="#333" @click="back"></tui-icon>
				</view>
			</tui-navigation-bar>
			<view class="userInfoEditTop"> </view>
		</view>
		<tui-landscape :show="landscapeShow" :closeIcon="false" :maskClosable="false" iconLeft="50rpx" iconRight="50rpx">
		</tui-landscape>
		<view class="userInfoEdit_Content">
			<view class="img_header">
				<view class="img_opt_header">
					<image class="optImg" :src="ossUrl + (shopDetails.masterImg||'')" alt="" />
				</view>
				<image @tap="uploadImg" class="icon_camera" src="/static/tutor/message/icon_photo@2x.png" alt="" />
			</view>
			<view class="form_my">
				<view class="item_info">
					<view class="label_info">店铺名称</view>
					<view class="comp_info">
						<tui-input inputBorder radius="16" padding="22rpx 40rpx" :color="'rgba(102, 102, 102, 1)'" size="28"
							:borderColor="'rgba(243, 230, 211, 1)'" isFillet :backgroundColor="'#FFFEF8'" placeholder="请输入姓名"
							v-model="shopDetails.merchantName"></tui-input>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">所属分类</view>
					<view class="comp_info">
						<view class="comp_infoSelect" @tap="showCategory=true">
							<view class="lt">
								{{ shopDetails.categoryName || className}}
							</view>
							<image class="rt" src="/static/tutor/message/icon_xiala@2x.png"></image>
						</view>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">店铺位置</view>
					<view class="comp_info">
						<view class="comp_infoSelect" @tap="selectAdress">
							<view class="lt">
								{{ shopDetails.address || shopDetails.poi&&shopDetails.poi.district}}
							</view>
							<image class="rt" src="/static/tutor/message/icon_xiala@2x.png"></image>
						</view>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">营业时间</view>
					<view class="comp_info">
						<view class="comp_infoSelect" @tap="showTime">
							<view class="lt" v-if="shopDetails.startTime.hour">
								<text>{{shopDetails.startTime.hour+':'+shopDetails.startTime.minute || '开始时间'}}</text>
								—
								<text>{{shopDetails.endTime.hour+':'+shopDetails.endTime.minute ||'结束时间'}}</text>
							</view>
							<view class="lt" v-else>
								<text>开始时间</text>
								—
								<text>结束时间</text>
							</view>
							<image class="rt" src="/static/tutor/message/icon_xiala@2x.png"></image>
						</view>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">店铺电话</view>
					<view class="comp_info">
						<tui-input inputBorder radius="16" padding="22rpx 40rpx" :color="'rgba(102, 102, 102, 1)'" size="28"
							:borderColor="'rgba(243, 230, 211, 1)'" isFillet :backgroundColor="'#FFFEF8'"
							v-model="shopDetails.contactNumber"></tui-input>
					</view>
				</view>

				<view class="item_info">
					<view class="label_info">图片({{imgs.length}})</view>
					<view class="comp_info">
						<view class="img" v-for="(img,i) in imgs" :key="i">
							<view class="infoBg">
								<image class="infoImg" :src="ossUrl + (img||'')"></image>
							</view>
							<image class="delImg" @tap="delImg(img,i)" src="/static/tutor/message/icon_del@2x (1).png"></image>
						</view>
						<view class="img" v-if="imgs.length<10" @tap="addImg">
							<image class="addImg" src="/static/tutor/message/icon_add1@2x.png"></image>
						</view>
						<!-- <view class="img" v-if="video">
						 	<view class="infoBg">
						 		 <image class="infoImg" :src="ossUrl + (video||'') +'?vframe/jpg/offset/1'"></image>
						 	</view>
						 	 <image class="delImg" @tap="delImg(video,i)" src="/static/tutor/message/icon_del@2x (1).png"></image>
						 </view>
						 <view class="img" v-if="!video" @tap="addVideo">
						 	 <image class="addImg" src="/static/tutor/message/icon_add1@2x.png"></image>
						 </view> -->
					</view>
				</view>
			</view>
		</view>
		<view class="footer">
			<tui-form-button :disabled="saveLoading" :loading="saveLoading" @click="saveShopInfo" margin="24rpx 0 0 0"
				radius="40rpx" size="32" color="#fff" width="690rpx" height="84rpx" background="#2FD7D3">
				保存
			</tui-form-button>
		</view>
		<tui-datetime :type="4" ref="dateTime" @confirm="changeTime"></tui-datetime>
		<tui-picker :valueField="'id'" :textField="'categoryName'" :show="showCategory" :pickerData="categoryList"
			@hide="showCategory=false" @change="change">
		</tui-picker>
	</view>
</template>

<script>
	import {
		getCategoryList
	} from "@/http/api/category/category.js"
	import {
		putShopList
	} from "@/http/api/shop/shop.js"
	import {
		delUploadFile
	} from "@/http/api/uploadFiles/uploadFiles.js"
	import Cache from '@/utils/cache'
	export default {
		data() {
			return {
				top: 0, //标题图标距离顶部距离
				marginTp: 0,
				ossUrl: getApp().globalData.ossurl,
				landscapeShow: false,
				saveLoading: false, //按钮加载
				shopDetails: {
					masterImg: '', //店铺主图
					merchantName: '', //店铺名称
					subhead: '', //副标题
					startTime: {
						hour: '',
						minute: ''
					}, //营业开始时间
					endTime: {
						hour: '',
						minute: ''
					}, //营业结束时间
					poi: {
						province: '',
						city: '',
						district: '',
						businessAreaName: '',
					}, //商圈信息
					address: '', //地址
					categoryId: '', //分类id
					categoryName: '', //分类名称 
					detailImgs: [], //商家图片
					contactNumber: '', //联系电话
					coordinates: {
						lng: '',
						lat: ''
					},

				}, //当前店铺信息
				imgs: [], //图片img
				video: '', //视频
				showCategory: false,
				categoryList: [], //分类
			}
		},
		onUnload() {
			uni.$off('adressInfo')
		},
		onLoad(options) {
			uni.$on('adressInfo', (e) => {
				this.shopDetails.address = e.address
				this.shopDetails.poi = e.poi
				if (!this.shopDetails.coordinates) {
					this.shopDetails.coordinates = {
						lng: '',
						lat: ''
					}
				}
				this.shopDetails.coordinates.lng = e.longitude
				this.shopDetails.coordinates.lat = e.latitude
			})
			this.shopDetails.coordinates.lng = Cache.get('longitude'),
				this.shopDetails.coordinates.lat = Cache.get('latitude')
			let shopData = JSON.parse(options.shopDetails)
			if (!shopData.address) {
				shopData.address = shopDetails.poi && shopDetails.poi.district
			}
			this.shopDetails = shopData
			if (shopData.detailImgs && shopData.detailImgs.length) {
				if (this.isImage(shopData.detailImgs[shopData.detailImgs.length - 1])) {
					this.imgs = shopData.detailImgs
				} else {
					if (shopData.detailImgs.length === 1) {
						this.video = shopData.detailImgs[0]
					} else {
						this.imgs = shopData.detailImgs.slice(0, -1)
						this.video = shopData.detailImgs[shopData.detailImgs.length - 1]
					}
				}
			}
			this.shopDetails.startTime = {
				hour: shopData.startTime ? shopData.startTime.split(':')[0] : '',
				minute: shopData.startTime ? shopData.startTime.split(':')[1] : ''
			}
			this.shopDetails.endTime = {
				hour: shopData.endTime ? shopData.endTime.split(':')[0] : '',
				minute: shopData.endTime ? shopData.endTime.split(':')[1] : ''
			}
			this.getCategorys()
		},
		computed: {
			className() {
				if (this.categoryList.length) {
					if (!this.shopDetails.categoryId) return
					let data = this.categoryList.filter(item => item.id === this.shopDetails.categoryId)
					return data[0].categoryName
				}
			}
		},
		methods: {
			isImage(filename) {
				const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'];
				const fileExtension = filename.slice(filename.lastIndexOf('.'));
				return imageExtensions.includes(fileExtension.toLowerCase());
			},
			//调用此方法显示选择器，需等组件初始化完成后调用，避免在onLoad中调用
			showTime: function(e) {
				this.$refs.dateTime && this.$refs.dateTime.show();
			},
			//选择分类
			change: function(e) {
				//选择的分类结果
				this.shopDetails.categoryId = e.id
				this.shopDetails.categoryName = e.result
			},
			//选择时间
			changeTime: function(e) {
				//选择的分类结果
				if (e.hour * 1 < this.shopDetails.startTime.hour * 1 && this.shopDetails.endTime.minute * 1 > 0) {
					this.shopDetails.startTime.hour = e.hour
					this.shopDetails.startTime.minute = e.minute
					return
				}
				if (this.shopDetails.startTime.hour) {
					this.shopDetails.endTime.hour = e.hour
					this.shopDetails.endTime.minute = e.minute
				} else {
					this.shopDetails.startTime.hour = e.hour
					this.shopDetails.startTime.minute = e.minute
				}

			},
			initNavigation(e) {
				this.top = e.top;
				this.marginTp = e.height
			},
			back() {
				uni.navigateBack({
					delta: 1
				});;
			},
			//上传商家主图
			uploadImg() {
				let _this = this;
				// uni.showLoading({
				// 	title: '上传中...'
				// })
				_this.landscapeShow = true
				_this.$utils.chooseMedia({
					count: 1, //
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					mediaType: ['image'], //选择类型
					success: async function(res) {
						_this.$utils.uploadFile(res.tempFilePaths[0], (imgInfo) => {
							if (imgInfo.statusCode == 200) {
								let dataImg = JSON.parse(imgInfo.data)
								_this.$utils.toast('上传成功')
								_this.$set(_this.shopDetails, 'masterImg', dataImg.data.fileName);
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'none',
									duration: 2000
								});
							}
							// uni.hideLoading()
							_this.landscapeShow = false
						})
					},
					complete: function(data) {
						uni.hideLoading()
						_this.landscapeShow = false
					}
				});
			},
			//获取分类列表
			getCategorys() {
				getCategoryList().then(res => {
					if (res.code) {
						this.categoryList = res.data
					}
				})
			},
			//选择店铺位置
			selectAdress() {
				let info = {
					latitude: this.shopDetails.coordinates && this.shopDetails.coordinates.lat || '39.54',
					longitude: this.shopDetails.coordinates && this.shopDetails.coordinates.lng || '116.25',
					name: this.shopDetails.address, // 名称
					address: this.shopDetails.address, // 详细地址
					businessAreaName: this.shopDetails.poi && this.shopDetails.poi.businessAreaName || '', // 商圈
					province: this.shopDetails.poi && this.shopDetails.poi.province || '', // 省份
					city: this.shopDetails.poi && this.shopDetails.poi.city || '', // 城市
					district: this.shopDetails.poi && this.shopDetails.poi.district || '', // 区县
				}
				uni.navigateTo({
					url: '/pages/tutorControl/modules/addressSelect/addressSelect?info=' + JSON.stringify(info)
				})
			},
			//上传视频
			addVideo() {
				uni.showLoading({
					title: '上传中...'
				})
				let _this = this;
				_this.landscapeShow = true
				_this.$utils.chooseMedia({
					count: 1,
					sourceType: ["camera", "album"],
					maxDuration: 30,
					mediaType: ["video"],
					success: (res) => {
						if (res.size / 1024 / 1024 > 50) {
							return uni.showToast({
								icon: "none",
								title: "拍摄视频过大，请重新拍摄！",
							});
						}
						_this.$utils.uploadFile(res.tempFilePaths[0], (videoInfo) => {
							if (videoInfo.statusCode == 200) {
								let dataVideo = JSON.parse(videoInfo.data)
								_this.video = dataVideo.data.fileName
								_this.$utils.toast('上传成功')
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'none',
									duration: 2000
								});
							}
							uni.hideLoading()
							_this.landscapeShow = false
						})
					},
					complete: function(data) {
						uni.hideLoading()
						_this.landscapeShow = false
					}
				});
			},
			//上传图片
			addImg() {
				uni.showLoading({
					title: '上传中...'
				})
				let _this = this;
				_this.landscapeShow = true
				_this.$utils.chooseMedia({
					count: 9, //
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					mediaType: ['image'], //选择类型
					success: async function(res) {
						// console.log(res)
						res.tempFilePaths.forEach(imgurl => {
							_this.$utils.uploadFile(imgurl, (imgInfo) => {
								if (imgInfo.statusCode == 200) {
									let dataImg = JSON.parse(imgInfo.data)
									_this.imgs.push(dataImg.data.fileName)
									_this.$utils.toast('上传成功')
								} else {
									uni.showToast({
										title: '上传失败',
										icon: 'none',
										duration: 2000
									});
								}
								uni.hideLoading()
								_this.landscapeShow = false
							})
						})

					},
					complete: function(data) {
						uni.hideLoading()
						_this.landscapeShow = false
					}
				});
			},
			//删除图片
			delImg(e, index) {
				let that = this
				let isVideo = e.indexOf("mp4") !== -1
				uni.showModal({
					title: "温馨提示",
					content: `确认删除该${isVideo?'视频':'图片'}吗?`,
					confirmText: "确认",
					showCancel: '取消',
					success: (res) => {
						if (res.confirm) {
							// let id= isVideo ?  that.video.ossId :that.imgs[index].ossId
							// delUploadFile(id).then(res=>{
							// 	if(res.code==200){
							// 		that.$utils.toast('删除成功') 
							// 		if(isVideo){
							// 			that.video={}
							// 		}else{ 
							// 		  that.imgs.splice(index, 1);
							// 		}
							// 	}else{
							// 		that.$utils.toast(res.msg)
							// 	}
							// })
							if (isVideo) {
								that.video = ''
							} else {
								that.imgs.splice(index, 1);
							}
							that.$utils.toast('删除成功')
						}
					},
				});
			},
			//保存商家编辑信息
			saveShopInfo() {
				let that = this
				if (!that.shopDetails.address) {
					that.$utils.toast('店铺位置不能为空')
					return false
				}
				that.saveLoading = true
				// let imgs= that.imgs
				// let detailImgs;
				// if(that.video){
				// 	detailImgs = imgs.concat([that.video])
				// }else{
				// 	detailImgs = imgs
				// }
				let startTime = that.shopDetails.startTime.hour + ':' + that.shopDetails.startTime.minute === ':' ? '' : that
					.shopDetails.startTime.hour + ':' + that.shopDetails.startTime.minute
				let endTime = that.shopDetails.endTime.hour + ':' + that.shopDetails.endTime.minute === ':' ? '' : that
					.shopDetails.endTime.hour + ':' + that.shopDetails.endTime.minute
				putShopList({
						masterImg: that.shopDetails.masterImg,
						merchantName: that.shopDetails.merchantName,
						startTime: startTime,
						endTime: endTime,
						poi: that.shopDetails.poi,
						address: that.shopDetails.address,
						detailImgs: that.imgs,
						coordinates: {
							lng: that.shopDetails.coordinates.lng,
							lat: that.shopDetails.coordinates.lat
						},
						contactNumber: that.shopDetails.contactNumber,
						categoryId: that.shopDetails.categoryId,
						id: that.shopDetails.id
					}).then(res => {
						if (res.code === 200) {
							that.$utils.toast('编辑成功')
							setTimeout(() => {
								uni.$emit('refresh', true)
								uni.navigateBack({
									delta: 1
								});;
							}, 300)
						}
					})
					.finally(() => {
						setTimeout(() => {
							that.saveLoading = false
						}, 500)
					})
			}
		},
	}
</script>

<style lang="scss" scoped>
	@import './merchantInfoEdit.scss';
</style>